package com.aikon.wht.multiThread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author haitao.wang
 */
public class TestOfCyclicBarrier {

    static CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "callback");
        }
    });

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {


        ExecutorService es = Executors.newFixedThreadPool(12);
        for (int i = 0;i<12;i++){
            int finalI = i;
            es.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() +" begin");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        System.out.println(Thread.currentThread().getName() + " numbersWaiting " + cyclicBarrier.getNumberWaiting());
                        System.out.println(Thread.currentThread().getName() +" wait");
                        cyclicBarrier.await();
                        System.out.println(Thread.currentThread().getName()+" end");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }



    }

}
